package top.codetheory.thread._004_ReentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: CodeTheory
 * @since: 2024/5/3 上午1:58
 **/
@Slf4j
public class _002_设置超时时间 {
    public static void main(String[] args) {
//        test1();
        test2();
    }

    /**
     * 如果在超时时间内没有获得锁, 就会返回false, 否则返回true <br>
     * 当睡眠时间为500ms的时候：<img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1714673126091-2024-5-302:05:26.png"  /> <br>
     * 当睡眠时间为2s的时候： <img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1714673051038-2024-5-302:04:11.png"  />
     */
    private static void test1() {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {

            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.info("获取锁失败");
                    return;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("获取锁成功");
        }, "t1");
        t1.start();
        lock.lock();
        log.info("main 获取锁成功");
        try {
            Thread.sleep(500);
//            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        lock.unlock();
        log.info("main end");
    }

    /**
     * <p>我把return注释掉了, 观察一个现象:
     * <p> <img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1714984782114-2024-5-616:39:42.png"  />
     * <p> 从图中可以看到, t1线程还是往后执行了他的逻辑, chat gpt是这么回复的
     * <p> <img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1714984871962-2024-5-616:41:12.png"  />
     */
    private static void test2() {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {

            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.info("获取锁失败");
//                    return;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("获取锁成功");
        }, "t1");
        t1.start();
        lock.lock();
        log.info("main 获取锁成功");
        try {
//            Thread.sleep(500);
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        lock.unlock();
        log.info("main end");
    }
}